package backend

import (
	"context"
	"fmt"
	"github.com/wailsapp/wails/v2/pkg/logger"
	wailsruntime "github.com/wailsapp/wails/v2/pkg/runtime"
	"os"
	"runtime"
	"strconv"
	"{{.ProjectName}}/backend/utils"
)

// App struct
type App struct {
	Ctx     context.Context
	log     logger.Logger
	Env     wailsruntime.EnvironmentInfo
	AppMeta struct {
		AppName          string
		AppVersion       string
		AppRootDir       string
		AppUserDataDir   string
		AppDataDir       string
		AppNewVersionDir string
		AppExe           string
		AppFileExt       string
		AppPluginUpdate  string
	}
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// Startup startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) Startup(ctx context.Context) {
	a.Ctx = ctx
	var err error
	a.Env = wailsruntime.Environment(ctx)
	err = a.initMeta()
	a.log = logger.NewFileLogger(a.AppMeta.AppDataDir + "/dockerview.log")
	if err != nil {
		a.log.Error(fmt.Sprintf("无法设置目录结构. 原因: %s", err))
	}
}
func (a *App) initMeta() error {
	_, fileExt := utils.GetUserOS()
	a.AppMeta.AppRootDir = GetRoot()
	a.AppMeta.AppName = APP_NAME
	a.AppMeta.AppVersion = APP_VERSION
	a.AppMeta.AppUserDataDir = GetUserData(a.Env.BuildType)
	a.AppMeta.AppDataDir = a.AppMeta.AppRootDir + "./.data"
	a.AppMeta.AppNewVersionDir = a.AppMeta.AppDataDir + "/NewVersion"
	a.AppMeta.AppExe = GetExe(a.Env.BuildType)
	a.AppMeta.AppFileExt = fileExt
	a.AppMeta.AppPluginUpdate = a.AppMeta.AppDataDir + "/" + PLUGIN_UPDATE_FILENAME + a.AppMeta.AppFileExt

	err := utils.DirectoryCreator(a.AppMeta.AppDataDir, a.AppMeta.AppNewVersionDir)
	if err != nil {
		return err
	}
	a.chackUpdatePlugin()
	return nil
}

func (a *App) chackUpdatePlugin() {
	has, _ := utils.PathExists(a.AppMeta.AppPluginUpdate)
	if !has {
		var options utils.DownloadOptions
		options.OnlinePath = fmt.Sprintf("%s/%s_%s_%s%s", PLUGIN_UPDATE_URL, PLUGIN_UPDATE_NAME, runtime.GOOS, runtime.GOARCH, a.AppMeta.AppFileExt)
		options.LocalPath = a.AppMeta.AppPluginUpdate
		options.FileName = PLUGIN_UPDATE_FILENAME + a.AppMeta.AppFileExt
		fmt.Println(options.OnlinePath)
		fmt.Println(options.LocalPath)
		fmt.Println(options.FileName)
		err := utils.DownloadFile(options, os.ModePerm)
		if err != nil {
			fmt.Println(err.Error())
		}
	}
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	pid := os.Getpid()
	fmt.Println(pid)
	a.log.Debug(strconv.Itoa(pid))
	//return fmt.Sprintf("Hello %s, It's show time!", name)
	return fmt.Sprintf("pid ==== %s", strconv.Itoa(pid))
}
